package com.panfeng.xcloud.component.trace.config;

import brave.Tracing;
import brave.http.HttpAdapter;
import brave.http.HttpClientParser;
import brave.http.HttpServerParser;
import brave.http.HttpTracing;
import brave.sampler.Sampler;
import com.panfeng.xcloud.component.trace.properties.ZipkinTraceProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import zipkin2.Span;
import zipkin2.reporter.AsyncReporter;
import zipkin2.reporter.Sender;
import zipkin2.reporter.okhttp3.OkHttpSender;

/**
 * HttpTracing配置类
 *
 * @author xiaobo
 * @date 2018-08-22
 */
@Configuration
@EnableConfigurationProperties({ ZipkinTraceProperties.class })
@Slf4j
public class HttpTracingConfig {

	@Autowired
	private ZipkinTraceProperties zipkinTraceProperties;

	@Bean
	public Sender sender() {
		return OkHttpSender.create(zipkinTraceProperties.getZipkin());
	}

	@Bean
	public AsyncReporter<Span> spanReporter() {
		 AsyncReporter<Span> spanReporter = AsyncReporter.create(sender());
		log.info(">>> 已经初始化AsyncReporter：{} <<<",spanReporter);
		return spanReporter;
	}

	@Bean
	public HttpTracing httpTracing(Tracing tracing) {
		HttpTracing httpTracing = HttpTracing.create(tracing);
		log.info(">>> 已经初始化HttpTracing：{} <<<",httpTracing);
		return httpTracing.toBuilder().serverParser(new HttpServerParser() {
			@Override
			public <Req> String spanName(HttpAdapter<Req, ?> adapter, Req req) {
				return adapter.path(req);
			}
		}).clientParser(new HttpClientParser() {
			@Override
			public <Req> String spanName(HttpAdapter<Req, ?> adapter, Req req) {
				return adapter.path(req);
			}
		}).build();
	}

	@Bean
	public Tracing tracing() {
		Tracing tracing = Tracing.newBuilder()
		.localServiceName(zipkinTraceProperties.getServiceName())
		.spanReporter(spanReporter())
		.sampler(Sampler.create(zipkinTraceProperties.getRate())).build();
		log.info(">>> 已经初始化Tracing：{} <<<",tracing);
		return tracing;
	}

}
